﻿using databaseoper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["username"] != null)
            {
                Response.Redirect("/Index.aspx");
            }
        }

        /// <summary>
        /// 判断用户名是否存在
        /// </summary>
        /// <returns>如果用户名存在返回True否则返回False</returns>
        private Boolean ExistUser(String username)
        {
            String sql = "select * from Users where username = @Username";
            SqlParameter[] parames = new SqlParameter[] {
                new SqlParameter("@Username",username),
            };
            DataSet data = SQLHelper.ExecuteDataset(SQLHelper.connStr, CommandType.Text, sql, parames);
            int userCount = data.Tables[0].Rows.Count;
            if (userCount > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 通过账号和密码来校验，存不存在此账号
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns>如果存在返回True，反之False</returns>
        private Boolean ExistUserByPwd(String username,String password)
        {
            String sql = "select * from Users where username = @Username and password = @Password";
            SqlParameter[] parames = new SqlParameter[] {
                new SqlParameter("@Username",username),
                new SqlParameter("@Password",password),
            };
            DataSet data = SQLHelper.ExecuteDataset(SQLHelper.connStr, CommandType.Text, sql, parames);
            int userCount = data.Tables[0].Select().ToArray().Length;
            if (userCount > 0)
            {
                return true;
            }
            return false;
        }

        protected void Login_Click(object sender, EventArgs e)
        {
            if(!(UsernameValid.IsValid && PasswordValid.IsValid))
            {
                return;
            }

            String username = UsernameText.Text;
            String password = PasswordText.Text;

            if(!ExistUser(username))
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "", "<script>layer.alert('用户名不存在！')</script>");
                return;
            }

            
            if(!ExistUserByPwd(username,password))
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "", "<script>layer.alert('用户名或密码错误！')</script>");
                return;
            }


            Session["username"] = username;
            Response.Redirect("/Index.aspx");
        }
    }
}